﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Users.WebSite.Register
{
	public partial class RegisterByEmail : PageBase
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (SiteConfig.RegisterMethod != RegisterMethod.ByEmail)
			{
				Response.Redirect("Index.aspx");
			}
		}

		protected void BtnOK_Click(object sender, EventArgs e)
		{
			string email = this.TbEmail.Text.Trim();
			string nickname = this.TbNickname.Text.Trim();
			string password = this.TbPassword.Text.Trim();
			string confirmPassword = this.TbConfirmPassword.Text.Trim();

			var userService = UsersSf.UserService;
			ErrorCode errorCode;

			if (!userService.CheckEmail(email, out errorCode))
			{
				this.Result.Failure(errorCode.Description);
				return;
			}

			if (!userService.CheckUsername(nickname, out errorCode))
			{
				this.Result.Failure(errorCode.Description);
				return;
			}

			if (password != confirmPassword)
			{
				this.Result.Failure("两次输入的密码不一致");
				return;
			}

			if (!Utility.ValidatePasswordFormat(password))
			{
				this.Result.Failure("密码不合法");
				return;
			}

			try
			{
				userService.CreateUserByEmail(email, password, nickname);
			}
			catch (UCException ex)
			{
				this.Result.Failure(ex.Message);
				return;
			}

			// 作为注册完成标识，在RegisterComplete.aspx页面中使用
			Session["RegisterCompleteAccount"] = email;
			Response.Redirect("RegisterByEmail2.aspx");
		}
	}
}